package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * ① 调用订单中心接口判断该操作订单资源是否具备，如果资源不具备，最大挂起时限每次不超过3个月-自然月（可前台选择）；
 * ② 如果资源具备，按自然日为单位申请挂起天数，最大挂起时限每次不超过7天-自然日；
 * ③ 挂起时限不能早于当天。
 */
@Service
public class HangDateAttrHandler extends AbstractAttrHandler {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Autowired
    private IInfServiceBus infServiceBus;

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        String lockOrReleaseOpType = querySceneInstService.getExtParameterValue(sceneInstId, "lockOrReleaseOpType");
        // 1：是 0：否
        String hangDate = "";
        if (KiteStringUtils.equals("LOCK", lockOrReleaseOpType)) {
            String result = "";
            // 调接口判断订单资源是否具备
            String orderId = querySceneInstService
                .getExtParameterValue(sceneInstId, "outOrderId");
            Map<String, Object> judgeResourcesRsp = infServiceBus.queryJudgeResources(orderId);
            if (KiteStringUtils.equals(KiteMapUtils.getString(judgeResourcesRsp, "code"), "0000")) {
                result = KiteMapUtils.getString(judgeResourcesRsp, "result");
            } else {
                result = "0";
            }
            // 1-资源具备 -0资源不具备
            if (KiteStringUtils.isNotEmpty(result) && KiteStringUtils.equals("1", result)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 7);
                Date today = calendar.getTime();
                hangDate = DateFormatUtils.formatDate(today, DateFormatUtils.DATE_FORMAT);
            } else if (KiteStringUtils.isNotEmpty(result) && KiteStringUtils.equals("0", result)) {
                hangDate = getHangDate();
            }
            commonAttr.setValue(hangDate);
            commonAttr.setValueDesc(hangDate);
        } else if (KiteStringUtils.equals("RELEASE", lockOrReleaseOpType)) {
            commonAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
            commonAttr.setIsNull(KeyConsts.IFTRUE_T);
        }
        setCommonAttr(commonAttr);
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        if (KiteStringUtils.isEmpty(value)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        String lockOrReleaseOpType = querySceneInstService.getExtParameterValue(sceneInstId, "lockOrReleaseOpType");
        if (KiteStringUtils.equals("LOCK", lockOrReleaseOpType)) {
            // A端要求完成时间/PE端要求完成时间
            KiteAttr aFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, "2_0000122");
            // Z端要求完成时间/CE端要求完成时间
            KiteAttr zFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, "2_0000123");
            // 全程要求完成时间
            KiteAttr allFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10012");
            if (Objects.nonNull(aFinishAttr)) {
                aFinishAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
                aFinishAttr.setIsNull(KeyConsts.IFTRUE_T);
                operateSceneCommonService.setCommonAttr(sceneInstId, aFinishAttr);
            }
            if (Objects.nonNull(zFinishAttr)) {
                zFinishAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
                zFinishAttr.setIsNull(KeyConsts.IFTRUE_T);
                operateSceneCommonService.setCommonAttr(sceneInstId, zFinishAttr);
            }
            if (Objects.nonNull(allFinishAttr)) {
                allFinishAttr.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
                allFinishAttr.setIsNull(KeyConsts.IFTRUE_T);
                operateSceneCommonService.setCommonAttr(sceneInstId, allFinishAttr);
            }
            // 当天
            String nowDate = DateFormatUtils.getFormatedDate();
            if (DateFormatUtils.compareDate(nowDate, value, DateFormatUtils.DATE_FORMAT) > 0) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("挂起时限不能早于当天");
            }
            String result = "";
            // 调接口判断订单资源是否具备
            String orderId = querySceneInstService
                .getExtParameterValue(sceneInstId, "outOrderId");
            Map<String, Object> judgeResourcesRsp = infServiceBus.queryJudgeResources(orderId);
            if (KiteStringUtils.equals(KiteMapUtils.getString(judgeResourcesRsp, "code"), "0000")) {
                result = KiteMapUtils.getString(judgeResourcesRsp, "result");
            } else {
                result = "0";
            }
            // 如果资源具备，最大挂起时限每次不超过7天-自然日
            if (KiteStringUtils.equals("1", result) && DateFormatUtils.getDayByStrs(nowDate, value, DateFormatUtils.DATE_FORMAT) > 7) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("资源具备时，最大挂起时限每次不超过7天-自然日");
            }
            // 如果资源不具备，最大挂起时限每次不超过3个月-自然月
            if (KiteStringUtils.equals("0", result)) {
                String hangDate = getHangDate();
                if (DateFormatUtils.getDayByStrs(hangDate, value, DateFormatUtils.DATE_FORMAT) > 0) {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("资源不具备时，最大挂起时限每次不超过3个月-自然月");
                }
            }
        } else if (KiteStringUtils.equals("RELEASE", lockOrReleaseOpType)) {
            KiteAttr handlerInfo = querySceneInstService.getCommonAttr(sceneInstId, fieldName);
            handlerInfo.setShowType(KeyConsts.PROD_ATTR_SHOW_TYPE_H);
            handlerInfo.setIsNull(KeyConsts.IFTRUE_T);
            operateSceneCommonService.setCommonAttr(sceneInstId, handlerInfo);
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    public String getHangDate() {
        String hangDate = "";
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        calendar.set(Calendar.MONTH, month + 3);
        calendar.set(Calendar.DATE, day);
        hangDate = sf.format(calendar.getTime());

        // 获取增加3月后的月份最后一天
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(Calendar.MONTH, month + 3);
        calendar2.set(Calendar.DAY_OF_MONTH, calendar2.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDayDate = sf2.format(calendar2.getTime());
        // 如果+3月后的日期>+3月后的最后一天，以最后一天为准
        if (DateFormatUtils.getDayByStrs(lastDayDate, hangDate, DateFormatUtils.DATE_FORMAT) > 0) {
            hangDate = lastDayDate;
        }
        return hangDate;
    }
}
